<script setup>
import { ref, reactive, onBeforeMount, onMounted, onBeforeUpdate, onUpdated, onBeforeUnmount, onUnmounted} from "vue"
import { useRoute,useRouter } from 'vue-router';
import UploadImg from '@/components/UploadImg/index.vue';
import TopBar from '@/components/Topbar/index.vue'
import getRules from "@/validUtils";
import {getProvinceCityArea} from '@/utils/area.js'
import { getCorporateInformation,editorialMerchant } from '@/api/BussinessMenage'
import {getAreaInfo,handleAddsChange} from './Hooks/index.js'
import { useDistInfoStore } from '@/stores/dict.js'
import { closeTag } from '@/utils/globalWay'



const topBar = ref(null)
const distInfoStore = useDistInfoStore();
const route = useRoute();
const router = useRouter()
const tabName = ref('编辑商户')
const backValue = ref('MerchantChildManageIndex')
const editLoading = ref(false)
const bussinessForm = ref({
  id:route.query.id || '',
  name: '', //商户名称
  busiGroupId: '', //商户分组
  busiWay:'', // 经营方式
  license:"",
  remark:'', //备注
  creditCode:'', //组织信用代码
  storeAddress:[],
  addressName:[], 
  password:'', //密码
  phone:'', //手机号
  linkman:'', //联系人
})

// 地址选择
const addressOptions = getAreaInfo()
// console.log(addressOptions,'addressOptions');

const handleAddsChanges = (val,list) => {
    let obj = {
        address:[],
        regionId:[]
  }
    handleAddsChange(val,list,bussinessForm.value,obj)
}

// 编辑回显数据
const getBackValue = async() => {
    editLoading.value = true
    try {
        let params = {
        id:route.query.id || ''
    }
        const res = await getCorporateInformation(params)
        console.log(res,'res');
        bussinessForm.value = {
            id:res.id || '',
            name: res.name || '', //商户名称
            busiGroupId: res.busiGroupId || '', //商户分组
            busiWay: res.busiWay, // 经营方式
            license:res.license || "", //许可证
            remark:res.remark || '', //备注
            creditCode: res.creditCode || '', //组织信用代码
            storeAddress: res.provinceCode ? [res.provinceCode,res.cityCode,res.areaCode] : [],
            addressName: res.province ? [res.province, res.city, res.area] : [], 
            phone:res.phone || '', //账号
            linkman: res.linkman || '', //联系人
        }
    } catch (error) {
        
    }finally{
        editLoading.value = false
    }
    

}

getBackValue()

// upload上传数据   
const backOcrValue = (ocrValue) => {
  console.log(ocrValue,'ocrValue');
  bussinessForm.value.license = ocrValue.fileUrl || ''
  bussinessForm.value.creditCode = ocrValue.licenseNumber || ''
}

const otherParams = ref({
  type:'129001'
})

const merchantGroupingData = computed(()=>{
    return distInfoStore.getDistInfos("商户分组").map(lis=>{
        return {
            value:lis.id,
            label:lis.permissionName
        }
    })
})

// 获取表单dom
const merchant = ref(null)
// 提交数据
const submit = () => {
    merchant.value.validate( async(valid) => {
        if(valid){
            try {
                editLoading.value = true
                let data = {
                ...bussinessForm.value,
                province:bussinessForm.value.addressName[0],
                city:bussinessForm.value.addressName[1],
                area:bussinessForm.value.addressName[2],
                provinceCode:bussinessForm.value.storeAddress[0],
                cityCode:bussinessForm.value.storeAddress[1],
                areaCode:bussinessForm.value.storeAddress[2],
            }
            // delete data.addressName
            // delete data.storeAddress
            console.log(data,'data');
            // return
            const res = await editorialMerchant(data)
            closeTag(route.name)
            router.push({name:'MerchantChildManageIndex'})
            ElMessage.success('编辑成功')
            } catch (error) {
                
            }finally{
                editLoading.value = false
            }
           
            
        }else{
            // to do list
        }
    })
}


const cancelBack = () => {
    topBar.value.backHandle()
    // merchant.value.resetFields()
}


//组件挂载到节点上之前执行的函数
onBeforeMount(()=>{})

//组件挂载完成后执行的函数
onMounted(()=>{})

//组件更新之前执行的函数
onBeforeUpdate(()=>{})

//组件更新完成之后执行的函数
onUpdated(()=>{})

//组件卸载之前执行的函数
onBeforeUnmount(()=>{})

//组件卸载完成后执行的函数
onUnmounted(()=>{})

</script>

<template>
  <div class="edit-page" v-loading="editLoading">
    <TopBar ref="topBar" :backValue="backValue" :tabName="tabName">
        <template #operate>
            <div>
                <el-button @click="cancelBack">取消</el-button>
                <el-button type="primary" @click="submit">确定</el-button>
            </div>
        </template>
    </TopBar>
    <div class="main">
        <el-form :inline="true" :model="bussinessForm" class="demo-form-inline" ref="merchant"  label-width="100px">
        <div class="basic">
            <div class="title-view">
                <div class="icon-view">
                    <div class="icon-view-on"></div>
                </div>
                <div class="title">基础信息</div>
            </div>
            <div class="basic-form">
                    <el-form-item label="商户名称" :rules="getRules('input','商户名称')" prop="name">
                    <el-input v-model="bussinessForm.name" placeholder="请输入" clearable  maxlength="50" show-word-limit/>
                    </el-form-item>
                    <el-form-item label="所属地区" :rules="getRules('select','所属地区')" prop="storeAddress">
                        <el-cascader
                        v-model="bussinessForm.storeAddress"
                        :options="addressOptions"
                        :props="{value:'area_code',label:'area_name',children:'children'}"
                        @change="(e)=>handleAddsChanges(e,addressOptions)"
                        style="width:100%"
                        clearable>
                    </el-cascader>
                    </el-form-item>
                    <el-form-item label="商户分组"  
                        :rules="getRules('select','商户分组')" 
                        prop="busiGroupId">
                    <el-select
                        v-model="bussinessForm.busiGroupId"
                        placeholder="请选择"
                        clearable
                    >
                    <el-option
                          v-for="it in merchantGroupingData"
                          :key="it.value"
                          :label="it.label"
                          :value="it.value"
                      />
                    </el-select>
                    </el-form-item>
                    <el-form-item label="联系人" prop="linkman" :rules="getRules('input','联系人')">
                        <el-input v-model="bussinessForm.linkman" 
                        placeholder="请输入联系人"
                        clearable 
                        maxlength="20" 
                        show-word-limit/>
                    </el-form-item>
               
            </div>
        </div>
        <div class="account-info">
            <div class="title-view">
                <div class="icon-view">
                    <div class="icon-view-on"></div>
                </div>
                <div class="title">账号信息</div>
            </div>

            <div class="account-form">
            
                    <el-form-item label="系统账号" prop="phone" :rules="getRules('phone', '手机号')">
                        <el-input v-model="bussinessForm.phone" placeholder="请输入11位有效手机号" clearable />
                    </el-form-item>
            </div>

        </div>
        <div class="business">
            <div class="title-view">
                <div class="icon-view">
                    <div class="icon-view-on"></div>
                </div>
                <div class="title">经营信息</div>
            </div>


                <div class="bussiness-form">
                    <el-form-item label="营业执照" style="margin-bottom: 32px;">
                        <UploadImg 
                            :action="'/gateway/jy-business/ocr/upload/ocrSingle'"
                            @backValue="backValuelicense" 
                            @backOcrValue="backOcrValue"
                            :imageUrlInfo="bussinessForm.license"
                            :maxImgLength="1"
                            :otherParams="otherParams"
                        >
                            <template #tips>
                                <div style="font-size:12px;color:#666;line-height:18px;margin-top:5px;position:absolute;width:260px">支持jpg、jpeg、png格式不超过5M</div>
                            </template>
                        </UploadImg>
                    </el-form-item>
                    <el-form-item style="margin-left: 192px;" label="经营方式" :rules="getRules('select','经营方式必填')" prop="busiWay">
                    <el-select
                        v-model="bussinessForm.busiWay"
                        placeholder="请输入"
                        clearable
                    >
                        <el-option label="直营" :value="1" />
                        <el-option label="加盟" :value="2" />
                    </el-select>
                    </el-form-item>
                    <el-form-item label="备注">
                        <el-input v-model="bussinessForm.remark" placeholder="请输入备注" clearable  maxlength="100" show-word-limit/>
                    </el-form-item>
                    <el-form-item label="组织信用代码">
                        <el-input v-model="bussinessForm.creditCode" placeholder="组织信用代码" clearable disabled/>
                    </el-form-item>
                </div>
        </div>
    </el-form>
    </div>
  </div>
</template>

<style lang="less" scoped>
    .edit-page{
        width: 100%;
        height: 100%;
        .main{
            width: 1700px;
            height: calc(100% - 48px);
            padding: 24px;
            overflow: auto;
            box-sizing: border-box;
             // 基础信息样式
         .basic{
            margin-bottom: 8px;

            .basic-form{
                margin-left: 20px;
            }
         
         }
        //  账户信息样式
         .account-info{
            margin-bottom: 8px;
            .account-form{
                margin-left: 20px;
            }
        // 经营信息样式
         }
         .business{
            margin-bottom: 8px;
            .bussiness-form{
                margin-left: 20px;
            }
         }
        }
       
    }
    .title-view{
                display: flex;
                align-items: center;
                margin-bottom: 16px;
                .icon-view{
                    margin-right: 8px;
                    position: relative;
                    width: 14px;
                    height: 14px;
                // background-color: red ;
                // background-repeat: no-repeat;
                // background-size: 7px 7px;
                    &::before {
                        content: "";
                        position: absolute;
                        top: 0;
                        left: 0;
                        width: 10px;
                        height: 10px;
                        border-radius: 2px;
                        background-color: #10E7F9; 
                    }
                    .icon-view-on{
                        position: absolute;
                        bottom: 0;
                        right: 0;
                        width: 10px;
                        height: 10px;
                        border-radius: 2px;
                        background-color: #3480FF; /* 背景色 */
                    }
            }
            .title{
                color: #000000;
                font-family: "PingFang SC";
                font-size: 14px;
                font-style: normal;
                font-weight: 600;
                line-height: 14px;
            }
            }

    .el-form-item{
        margin: 0 39px 16px 0;
        :deep(.el-input) {
          width: 350px;
        }
    }
</style>
